//
//  ClassCircleViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/6/7.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class ClassCircleViewController: BaseViewController ,UITableViewDelegate,UITableViewDataSource,MWPhotoBrowserDelegate,YcKeyBoardViewDelegate {
    
    var segmentedControl: UISegmentedControl!
    var tableView: UITableView!
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    var teacherArray = NSMutableArray()
    
    let top = 5
    var pageIndex = 1
    
    var photoArray = NSMutableArray()
    
    var key: YcKeyBoardView!
    var serid,senduid,preid,pretype: String!
    var apiurl = ""
    
    var hud: MBProgressHUD!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.title = "班级圈"
        
        InitViews()
        
        NotificationCenter.default.addObserver(self, selector: #selector(ClassWorkViewController.showBigImage(_:)), name: NSNotification.Name(rawValue: "showBigImage"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ClassWorkViewController.playvideo(_:)), name: NSNotification.Name(rawValue: "playvideo"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ClassCircleViewController.shareNotification(_:)), name: NSNotification.Name(rawValue: "shareWorkNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ClassWorkViewController.comment(_:)), name: NSNotification.Name(rawValue: "CommentWorkNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ClassWorkViewController.pariseWork(_:)), name: NSNotification.Name(rawValue: "pariseWorkNotification"), object: nil)
    }
    /**
     点赞
     
     - parameter notification:
     */
    func pariseWork(_ notification: Notification) {
        
        let queue = DispatchQueue(label: "queue")
        queue.async {
            
            let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
            let serid = dic.object(forKey: "serid") as! String
            let senduid = dic.object(forKey: "senduid") as! String
            let user = getUserPojo()
            let request = "\(requestHeader)27</t><serid>\(serid)</serid><sch>\(user.schid!)</sch><class>all</class><uid>\(user.userid!)</uid><senduserid>\(senduid)</senduserid></channel></rss>"
            var url = "\(server)/webapp/apps/schwebappapi.ashx"
            if self.apiurl != "" {
                url = self.apiurl
            }
            let result = HttpUtils.httpPostUTF(url, with: request)
            print("点赞地址\(url)\n\(request)\n返回\(result)")
            DispatchQueue.main.async(execute: {
                if result == "false" {
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "对不起，您已经点赞过，请不要重复点赞！", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                }else{
                    self.refreshThing()
                }
            })
        }
        
    }
    /**
     评论的编辑框和通知
     
     - parameter notification: <#notification description#>
     */
    func comment(_ notification: Notification) {
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        serid = dic.object(forKey: "serid") as! String
        preid = dic.object(forKey: "preid") as! String
        senduid = dic.object(forKey: "senduid") as! String
        pretype = dic.object(forKey: "typeid") as! String
        
        NotificationCenter.default.addObserver(self, selector: #selector(ClassWorkViewController.keyboardShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ClassWorkViewController.keyboardHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        if self.key == nil{
            self.key = YcKeyBoardView.init(frame: CGRect(x: 0, y: screenH - 44, width: screenW, height: 44))
        }
        self.key.delegate = self
        self.key.textView.becomeFirstResponder()
        self.key.textView.returnKeyType = UIReturnKeyType.send
        self.view.addSubview(self.key)
        
    }
    func keyboardShow(_ note: Notification) {
        let dic: Dictionary = note.userInfo!
        
        let keyBoardRect: CGRect = (dic[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue!
        let deltaY = keyBoardRect.size.height
        UIView.animate(withDuration: 1.0, animations: {
            self.key.transform = CGAffineTransform(translationX: 0, y: -deltaY)
        })
    }
    func keyboardHide(_ note: Notification) {
        UIView.animate(withDuration: 1.0, animations: {
            self.key.transform = CGAffineTransform.identity
        }, completion: { (Bool) in
            self.key.textView.text = ""
            self.key.removeFromSuperview()
        }) 
    }
    func keyBoardViewHide(_ keyBoardView: YcKeyBoardView!, textView contentView: UITextView!) {
        contentView.resignFirstResponder()
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if self.key != nil {
            self.keyBoardViewHide(self.key, textView: self.key.textView)
        }
    }
    /**
     发送评论
     
     - parameter text:评论的内容
     */
    func didSendCommentAction(_ text: String!) {
        self.keyBoardViewHide(self.key, textView: self.key.textView)
        let queue = DispatchQueue(label: "queue")
        queue.async {
            
            let user = getUserPojo()
            let request = "\(requestHeader)14</t><sch>\(user.schid!)</sch><class>all</class><uid>\(user.userid!)</uid><senduserid>\(self.senduid!)</senduserid><serid>\(self.serid!)</serid><Msg>\(text!)</Msg><preid>\(self.preid!)</preid><typeid>\(self.pretype!)</typeid></channel></rss>"
            var url = "\(server)/webapp/apps/schwebappapi.ashx"
            if self.apiurl != "" {
                url = self.apiurl
            }
            let result = HttpUtils.httpPostUTF(url, with: request)
            print("评论地址\(url)\n\(request)\n返回\(result)")
            
            DispatchQueue.main.async(execute: {
                if result == "True" {
                    //评论成功
                    self.refreshThing()
                }else{
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "评论失败。。。请检查网络稍后再试", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                }
                
            })
        }
    }
    func refreshThing(){
        let user = getUserPojo()
        var url = server + adminwebapppi
        let tops: String = String(top * pageIndex)
        let request = requestHeader + "5</t><sch>\(user.schid!)</sch><ClassID>all</ClassID><top>\(tops)</top><pagindex>1</pagindex></channel></rss>"
        if apiurl != "" {
            url = apiurl
        }
        workArray = getDataWithNoPost(url, request: request)
        tableView.reloadData()
    }
    /**
     分享
     
     - parameter notification:
     */
    func shareNotification(_ notification: Notification)  {
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        var title = dic.object(forKey: "title") as! String
        title = title.removingPercentEncoding!
        let serid = dic.object(forKey: "serid") as! String
        let username = dic.object(forKey: "TeaName") as! String
        let imageUrl = dic.object(forKey: "imageUrl") as! String
        var url = "\(server)/view/homework/apps/Staticshare.aspx?id=\(serid)"
        let user = getUserPojo()
        if self.apiurl.characters.count != 0 {
            url = url.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
        }
        let item1: ZYShareItem = ZYShareItem.init(title: "微信好友", icon: "wechat_L", handler: {
            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
            self.hud.animationType = MBProgressHUDAnimation.fade
            let queue = DispatchQueue(label: "queue")
            queue.async {
                
                print("分享到微信好友")
                let thumImage = "\(server)\(priImg)\(imageUrl.components(separatedBy: "|")[0].replacingOccurrences(of: "../..", with: ""))&width=300&mode=W"
                var data = try? Data.init(contentsOf: URL.init(string: thumImage)!)
                if data == nil || data?.count == 0{
                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
                }
                
                UMSocialData.default().extConfig.wechatSessionData.url = url
                UMSocialData.default().extConfig.wechatSessionData.title = "［\(appname)］班级圈 \(username)老师"
                let urlResource = UMSocialUrlResource.init()
                urlResource.setResourceType(UMSocialUrlResourceTypeWeb, url: url)
                DispatchQueue.main.async(execute: { 
                    UMSocialDataService.default().postSNS(withTypes: [UMShareToWechatSession], content: title, image: data, location: nil, urlResource: urlResource, presentedController: self, completion: { (shareResponse) in
                        if shareResponse?.responseCode == UMSResponseCodeSuccess {
                            print("分享微信好友成功")
                        }
                        print(shareResponse!)
                       
                    })
                     self.hud.hide(true)
                })
                
            }
            
        })
        let item2: ZYShareItem = ZYShareItem.init(title: "朋友圈", icon: "wechat_moment_L", handler: {
            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
            self.hud.animationType = MBProgressHUDAnimation.fade
            let queue = DispatchQueue(label: "queue")
            queue.async {
                print("分享到微信朋友圈")
                let thumImage = "\(server)\(priImg)\(imageUrl.components(separatedBy: "|")[0].replacingOccurrences(of: "../..", with: ""))&width=300&mode=W"
                var data = try? Data.init(contentsOf: URL.init(string: thumImage)!)
                if data == nil || data?.count == 0{
                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
                }
                UMSocialData.default().extConfig.wechatTimelineData.url = url
                let urlResource = UMSocialUrlResource.init()
                urlResource.setResourceType(UMSocialUrlResourceTypeWeb, url: url)
                DispatchQueue.main.async(execute: { 
                    UMSocialDataService.default().postSNS(withTypes: [UMShareToWechatTimeline], content: title, image: data, location: nil, urlResource: urlResource, presentedController: self, completion: { (shareResponse) in
                        if shareResponse?.responseCode == UMSResponseCodeSuccess {
                            print("分享微信朋友圈成功")
                        }
                        
                    })
                    self.hud.hide(true)
                })
                
            }
        })
//        let item3: ZYShareItem = ZYShareItem.init(title: "QQ好友", icon: "QQ_L", handler: {
//            
//            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
//            self.hud.animationType = MBProgressHUDAnimation.fade
//            
//            let queue = DispatchQueue(label: "queue")
//            queue.async {
//                print("分享qq好友")
//                let thumImage = "\(server)\(priImg)\(imageUrl.components(separatedBy: "|")[0].replacingOccurrences(of: "../..", with: ""))&width=300&mode=W"
//                var data = try? Data.init(contentsOf: URL.init(string: thumImage)!)
//                if data == nil || data?.count == 0{
//                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
//                }
//                UMSocialData.default().extConfig.qqData.title = "［桐乡教育］班级圈 \(username)老师"
//                UMSocialData.default().extConfig.qqData.url = url
//                DispatchQueue.main.async(execute: {
//                    UMSocialDataService.default().postSNS(withTypes: [UMShareToQQ], content: title, image: data, location: nil, urlResource: nil, presentedController: self, completion: { (shareResponse) in
//                        if shareResponse?.responseCode == UMSResponseCodeSuccess {
//                            print("分享qq成功")
//                        }
//                        
//                    })
//                    self.hud.hide(true)
//                })
//                
//            }
//            
//        })
//        let item4: ZYShareItem = ZYShareItem.init(title: "QQ空间", icon: "qzone_L", handler: {
//            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
//            self.hud.animationType = MBProgressHUDAnimation.fade
//            let queue = DispatchQueue(label: "queue")
//            queue.async {
//                let thumImage = "\(server)\(priImg)\(imageUrl.components(separatedBy: "|")[0].replacingOccurrences(of: "../..", with: ""))&width=300&mode=W"
//                var data = try? Data.init(contentsOf: URL.init(string: thumImage)!)
//                if data == nil || data?.count == 0{
//                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
//                }
//                UMSocialData.default().extConfig.qzoneData.title = "［桐乡教育］班级圈 \(username)老师"
//                UMSocialData.default().extConfig.qzoneData.url = url
//                DispatchQueue.main.async(execute: {
//                    UMSocialDataService.default().postSNS(withTypes: [UMShareToQzone], content: title, image: data, location: nil, urlResource: nil, presentedController: self, completion: { (shareResponse) in
//                        if shareResponse?.responseCode == UMSResponseCodeSuccess {
//                            print("分享qq空间成功")
//                        }
//                        
//                    })
//                    self.hud.hide(true)
//                })
//            }
//            
//        })
//        let item5 = ZYShareItem.init(title: "新浪微博", icon: "sina_weibo_L", handler: {
//            
//            self.hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
//            self.hud.animationType = MBProgressHUDAnimation.Fade
//            dispatch_async(dispatch_get_global_queue(0, 0), {
//                //微博原图
//                let thumImage = "\(server)\(imageUrl.componentsSeparatedByString("|")[0].stringByReplacingOccurrencesOfString("../..", withString: ""))"
//                var data = NSData.init(contentsOfURL: NSURL.init(string: thumImage)!)
//                if data == nil {
//                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
//                }
//                UMSocialDataService.defaultDataService().postSNSWithTypes([UMShareToSina], content: title + url, image: data, location: nil, urlResource: nil, presentedController: self, completion: { (shareResponse) in
//                    if shareResponse.responseCode == UMSResponseCodeSuccess {
//                        print("分享新浪微博")
//                    }else{
//                        print(shareResponse.data)
//                    }
//                    self.hud.hide(true)
//                })
//            })
//        })
        let shareView = ZYShareView.init(shareItems: [item1,item2], functionItems: nil)
        shareView?.show()
        
        
    }
    /**
     播放视频
     
     - parameter notification:
     */
    func playvideo(_ notification: Notification) {
        photoArray = NSMutableArray()
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let imageUrl = dic.object(forKey: "url") as! String
        var url = server + imageUrl.replacingOccurrences(of: "../..", with: "")
        let user = getUserPojo()
        if self.apiurl != "" {
            url = url.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
        }
        let video = MWPhoto.init(image: UIImage.init(named: "vdimg"))
        video?.videoURL = URL.init(string: url)
        photoArray.add(video)
        let browser: MWPhotoBrowser = MWPhotoBrowser.init(delegate: self)
        // Set options
        browser.displayActionButton = true; // Show action button to allow sharing, copying, etc (defaults to YES)
        browser.displayNavArrows = false; // Whether to display left and right nav arrows on toolbar (defaults to NO)
        browser.displaySelectionButtons = false; // Whether selection buttons are shown on each image (defaults to NO)
        browser.zoomPhotosToFill = true; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
        browser.alwaysShowControls = false; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
        browser.enableGrid = true; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
        browser.startOnGrid = false; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
        browser.autoPlayOnAppear = false; // Auto-play first video
        
        // Customise selection images to change colours if required
        //        browser.customImageSelectedIconName = @"ImageSelected.png";
        //        browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
        //
        //        // Optionally set the current visible photo before displaying
        browser.setCurrentPhotoIndex(0)
        self.navigationController?.pushViewController(browser, animated: true)
        browser.showNextPhoto(animated: true)
        browser.showPreviousPhoto(animated: true)
    }
    /**
     显示大图
     
     - parameter notification: <#notification description#>
     */
    func showBigImage(_ notification: Notification) {
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let imageUrl = dic.object(forKey: "url") as! String
        let index = UInt(dic.object(forKey: "index") as! String)
        let array = imageUrl.components(separatedBy: "|") as NSArray
        let array1 = NSMutableArray()
        array1.addObjects(from: array as [AnyObject])
        let n = array1.count
        photoArray = NSMutableArray()
        for i in 0...n-1 {
            var url = array1.object(at: i) as! String
            url = server + url.replacingOccurrences(of: "../..", with: "")
            let user = getUserPojo()
            if self.apiurl.characters.count != 0 {
                url = url.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
            }
            photoArray.add(MWPhoto.init(url: URL.init(string: url)))
            
        }
        let browser: MWPhotoBrowser = MWPhotoBrowser.init(delegate: self)
        // Set options
        browser.displayActionButton = true; // Show action button to allow sharing, copying, etc (defaults to YES)
        browser.displayNavArrows = false; // Whether to display left and right nav arrows on toolbar (defaults to NO)
        browser.displaySelectionButtons = false; // Whether selection buttons are shown on each image (defaults to NO)
        browser.zoomPhotosToFill = true; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
        browser.alwaysShowControls = false; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
        browser.enableGrid = true; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
        browser.startOnGrid = false; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
        browser.autoPlayOnAppear = false; // Auto-play first video
        
        // Customise selection images to change colours if required
        //        browser.customImageSelectedIconName = @"ImageSelected.png";
        //        browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
        //
        //        // Optionally set the current visible photo before displaying
        browser.setCurrentPhotoIndex(index!)
        self.navigationController?.pushViewController(browser, animated: true)
        browser.showNextPhoto(animated: true)
        browser.showPreviousPhoto(animated: true)
    }
    func numberOfPhotos(in photoBrowser: MWPhotoBrowser!) -> UInt {
        return UInt(photoArray.count)
    }
    func photoBrowser(_ photoBrowser: MWPhotoBrowser!, photoAt index: UInt) -> MWPhotoProtocol! {
        
        if index < UInt(photoArray.count) {
            
            return photoArray.object(at: Int(index)) as! MWPhoto
            
        }
        
        return nil;
    }
    func InitViews(){
        
        let array = ["全校发布","班级排行","教师排行"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 30, y: 74, width: screenW - 60, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(ClassWorkViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)
        
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
        setUpRefresh()
        
    }
    func setUpRefresh() {
        if mark == "1" || mark == "3"{
            
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(ClassWorkViewController.refresh))
            tableView.footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(ClassWorkViewController.loadMore))
            self.tableView.header.beginRefreshing()
        }else {
            
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(ClassWorkViewController.refresh))
            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }
        
    }
    /**
     刷新数据
     t=5   全校活动
     XmlNode schseridxml = ndoc.SelectSingleNode("//rss/channel/sch");
     XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
     XmlNode pagcountxml = ndoc.SelectSingleNode("//rss/channel/pagindex");
     */
    
    func refresh() {
        
        let user = getUserPojo()
        var url = server + adminwebapppi
        if apiurl != "" {
            url = apiurl
        }
        /**
         *  全校班级圈
         */
        if mark == "1" {
            pageIndex = 1
            let page: String = String(pageIndex)
            
            let request = "\(requestHeader)31</t><sch>\(user.schid!)</sch><top>\(top)</top><pagindex>\(page)</pagindex></channel></rss>"
            
            HttpPostUTF(url, requestXML: request, finished: { (data, result, error) in
                if error == nil {
                    
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)["post"]
                    if array.count != 0 {
                        self.workArray = NSMutableArray()
                        self.workArray.addObjects(from: array.arrayValue)
                    }
                    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
                }else {
                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                }
                self.tableView.reloadData()
                print("tableView.frame1 = \(self.tableView.frame)")
                self.tableView.header.endRefreshing()
            })
            
        }else if mark == "2" {
            let request = requestHeader + "34</t><sch>" + user.schid + "</sch></channel></rss>"
            
            HttpPostUTF(url, requestXML: request, finished: { (data, result, error) in
                if error == nil {
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                    if array.count != 0 {
                        self.classArray = NSMutableArray()
                        self.classArray.addObjects(from: array.arrayValue)
                    }
                }else {
                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                }
                
                self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
                self.tableView.reloadData()
                print("tableView.frame2 = \(self.tableView.frame)")
                self.tableView.header.endRefreshing()
            })
            
            
            
        }else if mark == "3" {
//            班级圈，排行排（只限教师用户的）
//            t=33
//            XmlNode schseridxml = ndoc.SelectSingleNode("//rss/channel/sch");
//            XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
//            XmlNode pagcountxml = ndoc.SelectSingleNode("//rss/channel/pagindex");
            pageIndex = 1
            let page: String = String(pageIndex)
            let request = requestHeader + "33</t><sch>" + user.schid + "</sch><top>20</top><pagindex>\(page)</pagindex></channel></rss>"
            HttpPostUTF(url, requestXML: request, finished: { (data, result, error) in
                if error == nil {
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                    if array.count != 0 {
                        self.teacherArray = NSMutableArray()
                        self.teacherArray.addObjects(from: array.arrayValue)
                    }
                }else {
                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                }
                self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
                self.tableView.reloadData()
                self.tableView.header.endRefreshing()
                print("tableView.frame3 = \(self.tableView.frame)")
            })
            
        }
        
    }
    func loadMore() {
        let user = getUserPojo()
        var url = server + adminwebapppi
        if apiurl != "" {
            url = apiurl
        }
        pageIndex += 1
        let page: String = String(pageIndex)
        if mark == "1"{
            let request = "\(requestHeader)31</t><sch>\(user.schid!)</sch><top>\(top)</top><pagindex>\(page)</pagindex></channel></rss>"
            
            HttpPostUTF(url, requestXML: request, finished: { (data, result, error) in
                if error == nil {
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)["post"]
                    if array.count != 0 {
                        self.workArray.addObjects(from: array.arrayValue)
                    }
                    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
                }else {
                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                }
                self.tableView.reloadData()
                self.tableView.footer.endRefreshing()
            })
        }else if mark == "2" {
            
        }else if mark == "3" {
            let request = requestHeader + "33</t><sch>" + user.schid + "</sch><top>20</top><pagindex>\(page)</pagindex></channel></rss>"
            HttpPostUTF(url, requestXML: request, finished: { (data, result, error) in
                if error == nil {
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                    if array.count != 0 {
//                        self.teacherArray = NSMutableArray()
                        self.teacherArray.addObjects(from: array.arrayValue)
                    }
                }else {
                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                }
                self.tableView.reloadData()
                self.tableView.footer.endRefreshing()
            })
        }
        
        
    }
    /**
     选项切换
     */
    func selTab() {
        let n = segmentedControl.selectedSegmentIndex
        
        switch n {
        case 0:
            mark = "1"
            setUpRefresh()
            break
        case 1:
            mark = "2"
            setUpRefresh()
            break
        case 2:
            mark = "3"
            setUpRefresh()
            break
        default:
            break
        }
    }
    
    /**
     高度
     
     - parameter tableView: tableview
     - parameter indexPath: item
     
     - returns: 高度
     */
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            if (indexPath as NSIndexPath).row < workArray.count {
                let dic = workArray[indexPath.row] as! JSON
                
                let imageUrl = dic["url"].stringValue
                var title = dic["title"].stringValue
                title = title.removingPercentEncoding!
                var praiseName = ""
                let comment = NSMutableArray()
                let prlist = dic["prlist"]
                if prlist.count != 0 {
                    for i in 0..<prlist.count {
                        let dic = prlist[i]
                        var pname = dic["TeaName"].stringValue
                        let pType = dic["UserType"].stringValue
                        if pType == "T" {
                            pname = "\(pname)老师"
                        }else{
                            pname = "\(pname)家长"
                        }
                        praiseName = "\(praiseName),\(pname)"
                    }
                }
                if praiseName.characters.count > 0{
                    praiseName = (praiseName as NSString).substring(from: 1)
                    praiseName = "     \(praiseName)"
                    
                }
                let aclist = dic["aclist"]
                if aclist.count != 0 {
                    for i in 0..<aclist.count {
                        let dic = aclist[i]
                        
                        var username = dic["UserName"].stringValue
                        username = username.replacingOccurrences(of: " ", with: "")
//                        let userType = dic.objectForKey("UserType") as! String
                        var msg = dic["ReMsg"].stringValue
                        msg = msg.removingPercentEncoding!
                        var commentStr = ""
                        commentStr = "\(username): \(msg)"
//                        if userType == "T" {
//                            commentStr = "\(username)老师: \(msg)"
//                        }else{
//                            commentStr = "\(username)家长: \(msg)"
//                        }
                        comment.add(commentStr)
                        
                        let aclist1 = dic["aclist1"]
                        if aclist1.count != 0 {
                            for i in 0..<aclist1.count {
                                let dic = aclist1[i]
                                var username = dic["ReUsername"].stringValue
                                username = username.replacingOccurrences(of: " ", with: "")
//                                let usertype = dic.objectForKey("UserType") as! String
//                                if usertype == "T" {
//                                    username = "\(username)老师"
//                                }else{
//                                    username = "\(username)家长"
//                                }
                                var rusername = dic["UserName"].stringValue
                                rusername = username.replacingOccurrences(of: " ", with: "")
//                                let rusertype = dic.objectForKey("SendUserType") as! String
//                                if rusertype == "T" {
//                                    rusername = "\(rusername)老师"
//                                }else{
//                                    rusername = "\(rusername)家长"
//                                }
                                var msg = dic["ReplyMemo"].stringValue
                                msg = msg.removingPercentEncoding!
                                let commentStr = "\(username)回复\(rusername): \(msg)"
                                comment.add(commentStr)
                            }
                        }
                    }
                }
                var height: CGFloat = 0.0
                let array = imageUrl.components(separatedBy: "|") as NSArray
                
                height = getPhotoCollectionHeight(array)
                /// 头像，间隔，上下间隔，时间，图片等，内容
                var cellHeight: CGFloat = 10.0+35+(10+getLabelHeight(title, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 60))+(10+height)+(10+30)+5
                
                if praiseName.characters.count > 0 {
                    cellHeight += getLabelHeight(praiseName, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 40) + 5
                }
                if comment.count > 0 {
                    cellHeight += 5 + getCommentTableHeight(comment)
                }
                return cellHeight
            }else{
                return 0
            }
            
        }else if mark == "2" {
            return 60
        }else {
            return 60
        }
    }
    /**
     多少行
     
     - parameter tableView: tableview
     - parameter section:
     
     - returns: 行数
     */
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if mark == "1" {
            return workArray.count
        }else if mark == "2" {
            return classArray.count
        }else {
            return teacherArray.count
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if mark == "1" {
            let cellIdentifier = "ClassWorkTableViewCellIdentifier";
            if (indexPath as NSIndexPath).row < workArray.count {
                
                let dic = workArray[indexPath.row] as! JSON
                let cell = ClassCircleTableViewCell(dictionary: dic, apiUrl: apiurl, reuseIdentifier: cellIdentifier)
                cell.selectionStyle = UITableViewCellSelectionStyle.none;
                return cell
                
            }else {
                return UITableViewCell()
            }
            
            
        }else if mark == "2" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: ClassSendTableViewCell = ClassSendTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < classArray.count {
                
                let dic = classArray[indexPath.row] as! JSON
                let classname = dic["classname"].stringValue
                let count = dic["classcon"].stringValue
                
                cell.classname.text = classname
                cell.count.text = "发布：" + count
            }
            return cell
            
        }else {
            let cellIdentifier = "ClassCountTableViewCellIdentifier";
            
            let cell: StudentListTableViewCell = StudentListTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < teacherArray.count {
                
                let dic = teacherArray[indexPath.row] as! JSON
                let teaname = dic["teaname"].stringValue
                let count = dic["usercon"].stringValue
                var photo = dic["userphoto"].stringValue
                photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
                photo = server + photo
                cell.userTx.sd_setImage(with: URL.init(string: photo), placeholderImage: UIImage.init(named: "touxiangm"))
                cell.userName.text = teaname
                cell.count.text = "发布：" + count
            }
            
            return cell
            
        }
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if self.key != nil {
            self.keyBoardViewHide(self.key, textView: self.key.textView)
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

